﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MotionCS.Controller;

namespace MotionCS.Module
{
    public interface ISensor
    {
        /// <summary>
        /// 读取检测传感器1状态
        /// </summary>
        /// <returns></returns>
        void ReadStatus();
        /// <summary>
        /// 感应器是否触发
        /// </summary>
        /// <returns>true触发 false未触发</returns>
        bool IsOn();
    }

    public class SensorConfig
    {
        /// <summary>
        /// 传感器名称
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// 传感器输入
        /// </summary>
        public IDiBit Din { get; set; }
    }

    public class SensorFilter : ISensor
    {
        /// <summary>
        /// 感应器配置
        /// </summary>
        private SensorConfig sensorConfig;
        /// <summary>
        /// 感应器输入
        /// </summary>
        private IDiBit diBit;
        /// <summary>
        /// 感应器上个状态
        /// </summary>
        private bool preState = false;
        /// <summary>
        /// 感应器当前状态
        /// </summary>
        private bool curState;
        /// <summary>
        /// 开始时间
        /// </summary>
        private DateTime startTime;
        /// <summary>
        /// 构造函数
        /// </summary>
        public SensorFilter(SensorConfig config)
        {
            sensorConfig = config;
            diBit = config.Din;
            startTime = DateTime.Now;
        }
        /// <summary>
        /// 读取检测传感器1状态
        /// </summary>
        /// <returns></returns>
        public void ReadStatus()
        {
            bool state = diBit.IsOn();

            if (preState != state)
            {
                startTime = DateTime.Now;
                preState = state;
            }

            TimeSpan span = DateTime.Now - startTime;
            if (span.TotalMilliseconds >= 20)
            {
                curState = state;
            }
        }
        /// <summary>
        /// 感应器是否触发
        /// </summary>
        /// <returns>true触发 false未触发</returns>
        public bool IsOn()
        {
            return curState;
        }
    }
}
